package com.itheima.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.Book;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller

@RestController
public class BookController {

    @RequestMapping("/spad1")
    public String showPageAndData1(HttpServletRequest req){
        req.setAttribute("name","itcast");
        return "resp2";
    }

    @RequestMapping("/spad2")
    public String spad2(Model model){
        //添加数据的方式，key对value
        model.addAttribute("name","anni");
        Book book=new Book();
        book.setName("SpringMVC_quick");
        book.setPrice(66.55D);
        //添加数据的方式，key对value
        model.addAttribute("book",book);
        return "resp2";
    }

    @RequestMapping("/spad3")
    public ModelAndView spad3(ModelAndView modelAndView){
        Book book=new Book();
        book.setName("spad3的Name");
        book.setPrice(6.6D);

        //添加数据的方式，key对value
        modelAndView.addObject("book",book);
        //添加数据的方式，key对value
        modelAndView.addObject("name","Hsw");
        //设置页面的方式，该方法最后一次执行的结果生效
        modelAndView.setViewName("resp2");
        //返回值设定成ModelAndView对象
        return modelAndView;
    }


    @RequestMapping("/spad4")
    public ModelAndView spad4(ModelAndView modelAndView){
        modelAndView.setViewName("forward:/WEB-INF/page/resp2.jsp");
        return modelAndView;
    }


        @RequestMapping("/spad5")
    public ModelAndView spad5(ModelAndView modelAndView){
        modelAndView.setViewName("redirect:resp1.jsp");
        return modelAndView;
        }




    // JSON
    //基于response返回数据的简化格式，返回JSON数据
  @RequestMapping("/spad6")
    public String spad6() throws JsonProcessingException {
        Book book=new Book();
        book.setName("json");
        book.setPrice(66.6D);

      ObjectMapper om=new ObjectMapper();
      return om.writeValueAsString(book);
  }

  //使用SpringMVC提供的消息类型转换器将对象与集合数据自动转换为JSON数据
    @RequestMapping("/spad7")
    @ResponseBody
    public Book spad7(){
        Book book=new Book();
        book.setName("SpringMVC入门案例");
        book.setPrice(66.66d);
        return book;
    }








}
